package juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

class MyLock{//自己定义一个自旋锁
    //原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+" 线程进入");
        while (!atomicReference.compareAndSet(null,thread)){
           // System.out.print(Thread.currentThread().getName()+" 线程等待");
        }
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+" 线程离开");
    }
}

class CeSuo implements Runnable{
    MyLock lock = new MyLock();
    @Override
    public void run() {
        lock.lock();
        //模拟访问共享资源
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
    }
}

public class MySelfLock {
    public static void main(String[] args) {
        CeSuo cesuo = new CeSuo();
        Thread t1 = new Thread(cesuo);
        Thread t2 = new Thread(cesuo);
        t1.start();
        t2.start();
        /*
        Thread-0 线程进入
        Thread-1 线程进入
        .....Thread1等待中（自选)
        Thread-0 线程离开
        Thread-1 线程离开
         */
    }
}
